﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;

namespace SynoManager.FileStation.Tasks
{
    public class CopyTask : TaskBase
    {
        private readonly IRemoteLocation source;
        private readonly DirectoryInfo target;
        private readonly string filename;
        private readonly bool overwrite;

        public CopyTask(IRemoteLocation source, DirectoryInfo target, bool overwrite)
        {
            this.source = source;
            this.target = target;
            this.filename = source.Name;
            this.overwrite = overwrite;
        }

        public override void Execute()
        {
            Debug.WriteLine("Copying " + source.RelativePath + " to " + target.RelativePath, "CopyTask");

            FileStationClient client = Queue.Service.client;
            var result = client.Copy(source.RelativePath, target.RelativePath, overwrite);
            int pid = result.pid;
            Debug.WriteLine("Task sent to device, retrieved pid #" + pid + ", running = " + result.running, "CopyTask");

            bool isRunning = result.running > 0;
            while (isRunning)
            {
                var progress = client.ReadMVCPProgress(pid);
                isRunning = progress.running > 0;

                Debug.WriteLine("#" + pid + ": " + progress.progress + " (running = " + progress.running + ")", "CopyTask");

                if (!isRunning)
                {
                    OnProgressChanged(progress.progress);
                    Thread.Sleep(1000);
                }
            }

            OnCompleted();
        }

        public override string DisplayTitle
        {
            get { return "Copy " + filename; }
        }

        public override string DisplayDescription
        {
            get { return "To " + target.RelativePath; }
        }

        public override System.Drawing.Image DisplayImage
        {
            get { return Properties.Resources.page_white_copy; }
        }
    }
}
